import { NameSpace } from 'utils';
import exceed from 'utils/apimap';

const ns = NameSpace('groupIndex');
export const RECEIVE_GROUP_LIST = ns('RECEIVE_GROUP_LIST');
export const RECEIVE_GROUP_SUBLIST = ns('RECEIVE_GROUP_SUBLIST');
export const UPDATE_GROUP_SUBLIST = ns('UPDATE_GROUP_SUBLIST');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');
export const RECEIVE_CREATE_ACCESS = ns('RECEIVE_CREATE_ACCESS');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

// 将指定id的状态恢复初始值
export function updateSubGroupMap(id) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_GROUP_SUBLIST,
      data: id,
    });
  };
}

export function getGroups(page, per_page) {
  return (dispatch, getState) => {
    const state = getState().group.groupHome;
    const { pathResource } = getState().root.pageInfo;
    const { order_by, archived_repository, pageSize = 10 } = state;
    if (per_page) {
      updateData({
        isLoading: true,
        pageSize: per_page,
      })(dispatch);
    } else {
      updateData({
        isLoading: true,
      })(dispatch);
    }

    const promise = getProjectsAndGroupsPromise(
      pathResource.id,
      order_by,
      page,
      per_page || pageSize,
      archived_repository,
    );

    promise
      .then((res) => {
        const groupList = handleResList(res.slice(1));
        const total = res[0].amount;
        updateData({
          groupList,
          total,
          currentPage: page,
          isLoading: false,
        })(dispatch);
      })
      .catch((err) => {
        updateData({
          isLoading: false,
        })(dispatch);
        console.error(err);
      });
  };
}

function getProjectsAndGroupsPromise(
  id,
  order_by,
  page = 1,
  pageSize = 10,
  archived_repository = false,
) {
  return new Promise((resolve, reject) => {
    exceed
      .fetch({
        api: 'group.detail.list',
        data: {
          page,
          per_page: pageSize,
          order_by,
          archived_repository,
        },
        params: {
          id,
        },
      })
      .then((result) => {
        resolve(result);
      })
      .fail((err) => {
        reject(err);
      });
  });
}

// 接口格式转换
function handleResList(list) {
  // list每一项：{group: null, project: null, type: 'project'}
  return list.map((item) => {
    if (item.type && item.type.toLowerCase() === 'group') {
      return item.group;
    } else {
      return { ...item.project, type: 'project' };
    }
  });
}

// 根据id获取子组列表
export function getSubGroups(id) {
  return (dispatch, getState) => {
    const state = getState().group.groupHome;
    const { order_by } = state;

    dispatch({
      type: RECEIVE_GROUP_SUBLIST,
      data: {
        [id]: {
          list: [],
          total: 0,
          isLoadingSubGroup: true,
          isExpanded: false,
        },
      },
    });

    const promise = getProjectsAndGroupsPromise(id, order_by);

    promise
      .then((res) => {
        const list = handleResList(res.slice(1));
        const total = res[0].amount;
        dispatch({
          type: RECEIVE_GROUP_SUBLIST,
          data: {
            [id]: {
              list,
              total,
              isLoadingSubGroup: false,
              isExpanded: true,
            },
          },
        });
      })
      .catch((err) => {
        dispatch({
          type: RECEIVE_GROUP_SUBLIST,
          data: {
            [id]: {
              list: [],
              total: 0,
              isLoadingSubGroup: false,
              isExpanded: false,
            },
          },
        });
        console.error(err);
      });
  };
}

// 获取创建库和组的权限
export function getCreateAccess(cb) {
  return (dispatch, getState) => {
    const { pathResource } = getState().root.pageInfo;
    exceed
      .fetch({
        api: 'groups.access.create_group_project',
        params: {
          groupId: pathResource.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_CREATE_ACCESS,
          data: result,
        });
        cb && cb();
      });
  };
}
